<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="utf-8" />
		<title>{$lang.add}|{$lang.edit}</title>
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<include file="common/ace-tag"/>
	</head>
	<link rel="stylesheet" href="/static/plugin/ace/css/chosen.css" />
	<script src="/static/plugin/ace/js/chosen.jquery.min.js"></script>
	<script src="/static/plugin/ace/js/jquery.autosize.min.js"></script>
	<script src="/static/plugin/ace/js/jquery.inputlimiter.1.3.1.min.js"></script>

	<link rel="stylesheet" type="text/css" href="/static/plugin/webuploader/webuploader.css">
	<link rel="stylesheet" type="text/css" href="/static/plugin/webuploader/style.css">
	<script type="text/javascript" src="/static/plugin/webuploader/webuploader.js"></script>
	<style>
		body{
			background-color:#fff
		}
		.yui_right{
			float: right;
			margin-bottom: 10px;
		}
	</style>
	<body >
	<div class="layui-form">
		<div class="widget-main">
			<input type="hidden" name="id" value="{$data.id}"/>
			<div>
				<label >{$lang_field['novel.title']}</label>
				<input type="text" name="title" <if condition="$method eq 'edit'">readonly</if> placeholder="{$lang_field['novel.title']}" class="form-control" value="{$data.title}"/>
				<br>
			</div>

			<div>
				<label >{$lang_field['author']}</label>
				<input type="text" name="author" placeholder="{$lang_field['author']}" class="form-control" value="{$data.author}"/>
				<br>
			</div>

			<div>
				<div id="uploader-demo">
					<!--用来存放item-->
					<div id="fileList" class="uploader-list">
						<?php if(!empty($data['icon'])) { ?>
							<div id="WU_FILE_0" class="file-item thumbnail">
								<img style="width: 100px;height: 100px" src="{$data.icon}"/>
								<div class="info">{$data.title}</div>
							</div>
						<?php } ?>
					</div>
					<div id="filePicker">{$lang.choosen_picker}</div>
				</div>
				<br>
			</div>

			<div>
				<label >{$lang_field['tags']}</label>
				<input type="text" onclick="cTags()" name="tags" placeholder="{$lang_field['tags']}" readonly class="form-control" value="{$data.tags}"/>
				<br>
			</div>

			<div >
				<label >{$lang_field.novel_status}</label>
				<select class="form-control" name="novel_status">
					<foreach name="$novel_status" item="v" key="k">
						<eq name="data.novel_status|default=2" value="$k">
							<option value="{$k}" selected>{$v}</option>
							<else/>
							<option value="{$k}">{$v}</option>
						</eq>
					</foreach>
				</select>
				<br>
			</div>

			<div >
				<label >{$lang_field.brief}</label>
				<textarea class="autosize-transition form-control" name="brief" >{$data.brief}</textarea>
				<br>
			</div>

			<button class="btn btn-primary yui_right" id="save">
				<i class="icon-plus align-top bigger-125"></i>
				{$lang.save}
			</button>


		</div>

		<div id="tagDiv" style="display: none;margin-top: 30px">
			<div class="layui-form-item">
				<div class="layui-input-block">
					<foreach name="$tags_list" item="v" key="k">
						<input type="checkbox" id="{$k}" name="tags_list" value="{$k}" title="{$v}">
					</foreach>
				</div>
			</div>
		</div>

	</div>


	</body>

	<script>
		$(function () {

            let tags='{$data.tags}'.split(',');
            for (i=0;i<tags.length;i++){
                $("#"+tags[i]).prop("checked", true);
            }

            initWebUploader();

            layui.use(['form'], function(){
            });

            $(".chosen-select").chosen();
            $('textarea[class*=autosize]').autosize({append: "\n"});
            $('textarea.limited').inputlimiter({
                remText: '%n character%s remaining...',
                limitText: 'max allowed : %n.'
            });

            //新增
            $("#save").on('click' , function(){
                let form= new FormData();
                let id=$("input[name='id']").val();
                let title=$("input[name='title']").val();
                let author=$("input[name='author']").val();
                let tags=$("input[name='tags']").val();
                let novel_status=$("select[name='novel_status']").val();
                let brief=$("textarea[name='brief']").val();
                form.append('method','{$method}');
                form.append('id',id);
                form.append('title',title);
                form.append('author',author);
                form.append('tags',tags);
                form.append('novel_status',novel_status);
                form.append('brief',brief);
                let images=uploader.getFiles();
                for (let i=0;i<images.length;i++){
                    form.append('image['+i+']',images[i]['source']['source']);//file
                }
                let loading = layer.load(1, {
                    shade: [0.1,'#fff']
                });
                $.ajax({
                    url : '{$__url}',
                    type : 'POST',
                    dataType:"json",
                    data : form,
                    // 告诉jQuery不要去处理发送的数据
                    processData : false,
                    // 告诉jQuery不要去设置Content-Type请求头
                    contentType : false,
                    success : function(data) {
                        if (data['code']==1){
                            layer.open({
                                title: '{$lang.notice}',
                                content: '{$lang.op_success}'
                                ,yes: function(index, layero){
                                    //关闭本子页面 & 触发重新查询
                                    parent.layer.close(parent.layer.getFrameIndex(window.name));
                                    let node = window.parent.document.getElementById("npe_search");
                                    node.click();
                                }
                            });
                        }else{
                            layer.msg(data['msg']);
                        }
                        layer.close(loading);
                    },
                    error : function(responseStr) {
                        console.log(responseStr);
                        layer.msg("{$lang.op_failed}",{time:1000});
                    }
                });
            });

        });
		
		function cTags() {
            $('#tagDiv').show();
            layer.open({
                type: 1
                ,offset: 'auto'
				,closeBtn: 0
				,title: '{$lang.notice}'
                ,id: 'layTags' //防止重复弹出
                ,area: ['600px','400px']
                ,content: $('#tagDiv')
                ,shadeClose: true
                ,end:function () {
                    let check_arr = [];
                    $('input[name=tags_list]:checked').each(function(){
                        check_arr.push($(this).val());
                    });
                    $("input[name='tags']").val(check_arr.join(','));
                    $("#tagDiv").hide();
                    layer.closeAll();
                }
            });
        }

        /*
		* 初始化上传插件
		* */
        function initWebUploader() {
            let $ = jQuery,
                $list = $('#fileList'),
                // 优化retina, 在retina下这个值是2
                ratio = window.devicePixelRatio || 1,

                // 缩略图大小
                thumbnailWidth = 100 * ratio,
                thumbnailHeight = 100 * ratio;
            // 初始化Web Uploader
            uploader = WebUploader.create({
                swf: '/static/plugin/webuploader/js/Uploader.swf',
                server: '',
                pick: '#filePicker',
                fileNumLimit: 1,
                accept: {
                    title: 'Images',
                    extensions: 'gif,jpg,jpeg,bmp,png',
                    mimeTypes: 'image/*'
                }
            });

            // 当有文件添加进来的时候
            uploader.on( 'fileQueued', function( file ) {
                //已有图片处理
                if("{$data.icon}" != ''){
                    $list.empty();
				}
                //限制只能上传一张图片
                let images_length=uploader.getFiles().length;
                if (images_length>1) {
                    uploader.reset();
                    $list.empty();
                    uploader.addFile(file);
				} else {
                    let $li = $(
                        '<div id="' + file.id + '" class="file-item thumbnail">' +
                        '<img>' +
                        '<div class="info">' + file.name + '</div>' +
                        '</div>'
                        ),
                        $img = $li.find('img');
                    // $list为容器jQuery实例
                    $list.append( $li );
                    // 创建缩略图
                    uploader.makeThumb( file, function( error, src ) {
                        if ( error ) {
                            $img.replaceWith('<span>不能预览</span>');
                            return;
                        }
                        $img.attr( 'src', src );
                    }, thumbnailWidth, thumbnailHeight );
				}
            });
        }

	</script>

</html>
